package com.example.demo.util;

import com.example.demo.model.entity.Prize;

import java.util.*;

public class DrawUtil {

    /**
     * 使用别名算法选奖
     * @param prizeList
     * @return
     */
    public static Prize draw(List<Prize> prizeList) {
        //查询奖品中奖概率
        int totalProbability = 0;
        int num = 0;
        for(Prize prize : prizeList) {
            totalProbability += prize.getProbability();
            num ++;
        }

        //构建概率列表
        List<Double>  probabilities = new ArrayList<>();
        Collections.sort(prizeList, Comparator.comparingInt(Prize::getLevel));
        for(Prize prize : prizeList) {
            probabilities.add(prize.getProbability() * 1.0 / Constants.probabilityDivider);
        }

        //使用空奖，将总概率补充到1
        probabilities.add(1.0 - (totalProbability * 1.0 / Constants.probabilityDivider));

        //使用AliasMethod算法抽取奖品
        Random random = new Random();
        AliasMethod aliasMethod = new AliasMethod(probabilities, random);
        int prizeLevel = aliasMethod.next();
        if(prizeLevel == num) {
            //命中空奖
            return null;
        } else {
            return prizeList.get(prizeLevel);
        }
    }
}
